﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using System.Xml;
using System.IO;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;
using System.Collections;
using System.Configuration;
using Common;
using System.Diagnostics;

namespace ConfigManager
{
    public partial class Main : Form
    {
       
        #region 初始化
    
        public Main()
        {
            InitializeComponent();
            InitForm();
            this.tabControl1.DrawItem += new DrawItemEventHandler(tabControl1_DrawItem);
        }

        /// <summary>
        /// 自定义Tab标签颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            Font fntTab;
            Brush bshBack;
            Brush bshFore;

            if (e.Index == this.tabControl1.SelectedIndex)//激活的标签页
            {
                fntTab = new Font(new FontFamily("宋体"), 9);
                bshBack = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.White, Color.White, System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal);
                bshFore = Brushes.DarkBlue;
            }
            else//非激活的标签页
            {
                fntTab = new Font(new FontFamily("宋体"), 9);
                bshBack = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, SystemColors.Control, SystemColors.Control, System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal);
                bshFore = new SolidBrush(e.ForeColor);
            }

            string tabName = this.tabControl1.TabPages[e.Index].Text;
            StringFormat sftTab = new StringFormat();
            e.Graphics.FillRectangle(bshBack, e.Bounds);
            Rectangle recTab = e.Bounds;
            if (e.Index == this.tabControl1.SelectedIndex)//激活的标签页
            {
              recTab = new Rectangle(recTab.X+4, recTab.Y + 4, recTab.Width, recTab.Height - 4);
            }
            else//非激活的标签页
            {
              recTab = new Rectangle(recTab.X, recTab.Y+4, recTab.Width, recTab.Height-4);
            }
            
            e.Graphics.DrawString(tabName, fntTab, bshFore, recTab, sftTab);
            

        }

        private void Main_Load(object sender, EventArgs e)
        {
            LoadConfigTreeItem();
            InitFiltering();
            LoadControlTempTreeItem();
            BindInsertCodeTreeItem();
            tree2.ExpandAll();
        }

        private void LoadConfigTreeItem()
        {
            try
            {
                tree1.ImportFromXml(PubConstant.ConfigPath + PubConstant.ConfigManagerName);                
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("ConfigManager-InitConfigTreeItem()", ex);
                throw;
            }
        }

        private void InitFiltering()
        {
            tree1.FilterConditions.Add(new FilterCondition(FilterConditionEnum.Contains, tree1.Columns["Type"], "c",null, true));
            tree1.FilterConditions.Add(new FilterCondition(FilterConditionEnum.Contains, tree1.Columns["Type"], "m",null, true));
        }

        private void LoadControlTempTreeItem()
        {
            try
            {
                tree2.Nodes.Clear();
                DirectoryInfo di=new DirectoryInfo(PubConstant.TemplatePath);
                foreach(FileInfo fi in di.GetFiles("*-*.xml"))
                {
                    string typeName=fi.Name.Split('-')[0];
                    TreeListNode typeNode=tree2.FindNodeByFieldValue("ControlTempName",typeName);
                    if(typeNode==null)
                    {
                        typeNode=tree2.AppendNode(null,null);
                        typeNode.SetValue(0,typeName);
                        typeNode.SetValue(1,"Folder");
                    }
                    TreeListNode tln=tree2.AppendNode(null,typeNode.Id);
                    tln.SetValue(0,fi.Name.Substring(0,fi.Name.Length-4));
                }
                tree2.ExpandAll();
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("ConfigManager-InitControlTempTreeItem", ex);
                throw;
            }
        }

        private void InitForm()
        {
            try
            {
                IDictionary syntaxModes = GetOption.GetConfigDict("SyntaxModes") as IDictionary;
                if (syntaxModes != null)
                {
                    foreach (string key in syntaxModes.Keys)
                    {
                        ToolStripMenuItem miNewMode = new ToolStripMenuItem
                        {
                            Name = "mi" + key,
                            Text = key,
                            Tag = syntaxModes[key]
                            /*this.miNewMode.Size = new System.Drawing.Size(174, 22);*/
                        };

                        miNewMode.Click += (sender, e) =>
                        {
                            ToolStripMenuItem miThis = sender as ToolStripMenuItem;
                            if (miThis != null && miThis.Tag != null)
                            {
                                ToolStripDropDownMenu owner = miThis.Owner as ToolStripDropDownMenu;
                                if (owner != null && owner.Items.Count > 0)
                                {
                                    foreach (ToolStripMenuItem mi in owner.Items)
                                        mi.Checked = false;
                                    miThis.Checked = true;
                                }
                                if (currentEditor != null)
                                    currentEditor.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(miThis.Tag as string);
                            }
                        };

                        if (currentEditor != null)
                        {
                            if (key == "XML")
                            {
                                miNewMode.Checked = true;
                                currentEditor.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy("XML");
                            }
                        }
                        this.tsMILanguage.DropDownItems.Add(miNewMode);
                    }
                }
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("ConfigManager-InitForm()", ex);
                throw;
            }
            //if (currentEditor.TextEditorProperties == null)
            //{
            //    currentEditorSetting = currentEditor.TextEditorProperties;
            //    OnSettingsChanged();
            //}
            //else
            //{
            //    currentEditor.TextEditorProperties = currentEditorSetting;
            //}
            //UpdateFolding();
        }


        #endregion


        #region 方法

        /// <summary>
        /// Replaces the entire text of the xml view with the xml in the
        /// specified. The xml will be formatted.
        /// </summary>
        public void FormatXml(string xml)
        {
            string formattedXml = IndentedFormat(SimpleFormat(IndentedFormat(xml)));
            currentEditor.Document.Replace(0, currentEditor.Document.TextLength, formattedXml);
            UpdateFolding();
        }

        /// <summary>
        /// Returns a formatted xml string using a simple formatting algorithm.
        /// </summary>
        static string SimpleFormat(string xml)
        {
            return xml.Replace("><", ">\r\n<");
        }

        /// <summary>
        /// Returns a pretty print version of the given xml.
        /// </summary>
        /// <param name="xml">Xml string to pretty print.</param>
        /// <returns>A pretty print version of the specified xml.  If the
        /// string is not well formed xml the original string is returned.
        /// </returns>
        string IndentedFormat(string xml)
        {
            string indentedText = String.Empty;

            try
            {
                using (XmlTextReader reader = new XmlTextReader(new StringReader(xml)) { WhitespaceHandling = WhitespaceHandling.None })
                {
                    using (StringWriter indentedXmlWriter = new StringWriter())
                    {
                        XmlTextWriter writer = CreateXmlTextWriter(indentedXmlWriter);
                        writer.WriteNode(reader, false);
                        writer.Flush();

                        indentedText = indentedXmlWriter.ToString();
                    }
                }
            }
            catch (Exception)
            {
                indentedText = xml;
            }

            return indentedText;
        }

        XmlTextWriter CreateXmlTextWriter(TextWriter textWriter)
        {
            XmlTextWriter writer = new XmlTextWriter(textWriter);
            if (currentEditor.TextEditorProperties.ConvertTabsToSpaces)
            {
                //writer.Indentation = currentEditor.TextEditorProperties.IndentationSize;
                writer.IndentChar = ' ';
            }
            else
            {
                writer.Indentation = 1;
                writer.IndentChar = '\t';
            }
            writer.Formatting = Formatting.Indented;
            return writer;
        }

        /// <summary>
        /// Forces the editor to update its folds.
        /// </summary>
        void UpdateFolding()
        {
            currentEditor.Document.FoldingManager.UpdateFoldings(String.Empty, null);
            currentEditor.ActiveTextAreaControl.TextArea.Refresh();
        }
        #endregion

     
        #region 字段，属性

        //XmlDocument doc = null;
        TextEditorControl currentEditor;
        //ITextEditorProperties currentEditorSetting;
        //string currentPath;

        
        #endregion


        #region 树控件
        

        private void tree1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = tree1.CalcHitInfo(new Point(e.X, e.Y));
            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell) return;
            if (e.Button != MouseButtons.Left) return;
            if (tree1.Nodes.Count < 1) return;


            string fileName=tree1.FocusedNode.GetValue(0).ToString();
            string fileNameEng = tree1.FocusedNode.GetValue(1).ToString();
            try
            {
                toolStripContainer1.Visible = true;
                
                if(tabControl1.TabPages.Count>0)
                {
                    for (int i=0; i< tabControl1.TabPages.Count;i++)
                    {
                        if (tabControl1.TabPages[i].Text == fileName)
                        {
                            tabControl1.SelectTab(i);
                            return;
                        }
                    }
                }

                string filePath;
                switch (tree1.FocusedNode.GetValue(2).ToString())
                {
                    case"c":
                        filePath=PubConstant.ConfigPath;
                        break;
                    case"t":
                        filePath=PubConstant.TemplatePath;
                        break;
                    default:
                        filePath="";
                        break;
                }
               
                TextEditorControl icTE= new TextEditorControl();
                icTE.SetHighlighting("XML");
                icTE.ShowVRuler = true;
                icTE.ShowTabs = true;
                icTE.ShowSpaces = true;
                icTE.ShowEOLMarkers = true;
                icTE.IsIconBarVisible = false;
                icTE.ShowInvalidLines = true;
                icTE.Encoding = Encoding.Unicode;
                icTE.IndentStyle = ICSharpCode.TextEditor.Document.IndentStyle.Smart;
                icTE.ContextMenuStrip = contextMenuStrip1;
                if (filePath != "")
                {
                    using (StreamReader sr = new StreamReader(String.Format("{0}{1}.xml",filePath,fileNameEng)))
                    {
                        icTE.Text = sr.ReadToEnd();
                    } 
                }
                icTE.Tag = String.Format("{0}{1}.xml", filePath, fileNameEng);
                icTE.Dock = DockStyle.Fill;
                icTE.TextEditorProperties.LineViewerStyle = LineViewerStyle.FullRow;
                icTE.Document.DocumentChanged += icTE_DocumentChanged;


                currentEditor = icTE;
                
                //初始化视图菜单选中状态
                OnSettingsChanged();

                //初始化代码折叠功能
                if (!(currentEditor.Document.FoldingManager.FoldingStrategy is XmlFoldingStrategy))
                {
                    currentEditor.Document.FoldingManager.FoldingStrategy = new XmlFoldingStrategy();
                }
                UpdateFolding();

                TabPage tpp = new TabPage(fileName);
                tpp.Controls.Add(icTE);
                tabControl1.TabPages.Add(tpp);
                tabControl1.SelectTab(tabControl1.TabPages.Count - 1);
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("ConfigManager-tree1_MouseDoubleClick", ex);
                throw ex;
            }
        }

        private void tree2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = tree1.CalcHitInfo(new Point(e.X, e.Y));
            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell) return;
            if (e.Button != MouseButtons.Left) return;
            if (tree2.Nodes.Count < 1) return;
            if (tree2.FocusedNode.Nodes.Count > 0)return;


            string fileName=tree2.FocusedNode.GetValue(0).ToString();
            try
            {
                toolStripContainer1.Visible = true;

                if (tabControl1.TabPages.Count > 0)
                {
                    for (int i = 0; i < tabControl1.TabPages.Count; i++)
                    {
                        if (tabControl1.TabPages[i].Text == fileName)
                        {
                            tabControl1.SelectTab(i);
                            return;
                        }
                    }
                }
                string filePath = PubConstant.TemplatePath;

                TextEditorControl icTE = new TextEditorControl();
                icTE.SetHighlighting("XML");
                icTE.ShowVRuler = true;
                icTE.ShowTabs = true;
                icTE.ShowSpaces = true;
                icTE.ShowEOLMarkers = true;
                icTE.IsIconBarVisible = false;
                icTE.ShowInvalidLines = true;
                icTE.Encoding = Encoding.Unicode;
                icTE.IndentStyle = ICSharpCode.TextEditor.Document.IndentStyle.Smart;
                icTE.ContextMenuStrip = contextMenuStrip1;
                if (filePath != "")
                {
                    using (StreamReader sr = new StreamReader(String.Format("{0}{1}.xml",filePath,fileName)))
                    {
                        icTE.Text = sr.ReadToEnd();
                    }
                }
                icTE.Tag = String.Format("{0}{1}.xml", filePath, fileName);
                icTE.Dock = DockStyle.Fill;
                icTE.TextEditorProperties.LineViewerStyle = LineViewerStyle.FullRow;
                icTE.Document.DocumentChanged += icTE_DocumentChanged;


                currentEditor = icTE;

                //初始化视图菜单选中状态
                OnSettingsChanged();

                //初始化代码折叠功能
                if (!(currentEditor.Document.FoldingManager.FoldingStrategy is XmlFoldingStrategy))
                {
                    currentEditor.Document.FoldingManager.FoldingStrategy = new XmlFoldingStrategy();
                }
                UpdateFolding();

                TabPage tpp = new TabPage(fileName);
                tpp.Controls.Add(icTE);
                tabControl1.TabPages.Add(tpp);
                tabControl1.SelectTab(tabControl1.TabPages.Count - 1);
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("ConfigManager-tree2_MouseDoubleClick", ex);
                throw ex;
            }
            //ControlTempName
        }

        private void icTE_DocumentChanged(object sender, DocumentEventArgs e)
        {
            //刷新代码折叠状态
            currentEditor.Document.FoldingManager.UpdateFoldings(String.Empty, null);
        }


        #endregion


        #region TabControl控件
        
        /// <summary>
        /// 双击关闭，关闭以后激活它上面的一个Tab
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_DoubleClick(object sender, EventArgs e)
        {
            int indexT = tabControl1.SelectedIndex;
            foreach (Control cc in tabControl1.SelectedTab.Controls)
            {
                if (cc is TextEditorControl)
                {
                    if (!cc.IsDisposed)
                    {
                        cc.Dispose();
                    }
                    break;
                }
            }//释放TextEditorControl所占的大量内存
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
            if (tabControl1.TabPages.Count == 0)
            {
                toolStripContainer1.Visible = false;
            }
            else
            {
                if (indexT == 0)
                {
                    tabControl1.SelectedIndex = 0;
                }
                else
                {
                    tabControl1.SelectedIndex = indexT - 1;
                }
            }
        }


        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.TabCount > 0)
            {
                foreach (Control col in tabControl1.SelectedTab.Controls)
                {
                    if (col is TextEditorControl)
                    {
                        currentEditor = (TextEditorControl)col;
                        return;
                    }
                }
            }
        } 


        #endregion


        #region 双击打开关闭侧边栏

        private void splitContainer1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            splitContainer1.Panel1Collapsed = !splitContainer1.Panel1Collapsed;
        }

        private void tableLayoutPanel1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            splitContainer1.Panel1Collapsed = !splitContainer1.Panel1Collapsed;
        }
        #endregion


        #region 菜单
        
        private void DoEditAction(TextEditorControl editor, ICSharpCode.TextEditor.Actions.IEditAction action)
        {
            if (editor != null && action != null)
            {
                var area = editor.ActiveTextAreaControl.TextArea;
                editor.BeginUpdate();
                try
                {
                    lock (editor.Document)
                    {
                        action.Execute(area);
                        if (area.SelectionManager.HasSomethingSelected && area.AutoClearSelection /*&& caretchanged*/)
                        {
                            if (area.Document.TextEditorProperties.DocumentSelectionMode == DocumentSelectionMode.Normal)
                            {
                                area.SelectionManager.ClearSelection();
                            }
                        }
                    }
                }
                finally
                {   
                    editor.EndUpdate();
                    area.Caret.UpdateCaretPosition();
                }
            }
        }

        private bool HaveSelection(TextEditorControl te)
        {
            var editor = te;
            return editor != null &&
                editor.ActiveTextAreaControl.TextArea.SelectionManager.HasSomethingSelected;
        }

        /// <summary>
        /// 状态
        /// </summary>
        private void OnSettingsChanged()
        {
            //this.tsMISplitWindows.Checked = currentEditor.TextEditorProperties.
            this.tsMISpace.Checked = currentEditor.TextEditorProperties.ShowSpaces;
            this.tsMILineR.Checked = currentEditor.TextEditorProperties.ShowEOLMarker;
            this.tsMILineNo.Checked = currentEditor.TextEditorProperties.ShowInvalidLines;
            this.tsMILineNum.Checked = currentEditor.TextEditorProperties.ShowLineNumbers; 
            this.tsMIHighLight.Checked = currentEditor.TextEditorProperties.LineViewerStyle == LineViewerStyle.FullRow;
            this.tsMIBracketMatchingStyle.Checked = currentEditor.TextEditorProperties.BracketMatchingStyle == BracketMatchingStyle.After;
            this.tsMITabToSpace.Checked = currentEditor.ConvertTabsToSpaces;
        }


        #region File
     
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMINew_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIOpen_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISave_Click(object sender, EventArgs e)
        {
            foreach (Control cc in tabControl1.SelectedTab.Controls)
            {
                if (cc is TextEditorControl)
                {
                    TextEditorControl tec=(TextEditorControl)cc;
                    string path = tec.Tag.ToString();
                    tec.SaveFile(path);
                    break;
                }
            }


        }
        /// <summary>
        /// 另存为
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISaveAS_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (Control cc in tabControl1.SelectedTab.Controls)
                {
                    if (cc is TextEditorControl)
                    {
                        TextEditorControl tec = (TextEditorControl)cc;
                        tec.SaveFile(saveFileDialog1.FileName);
                        break;
                    }
                }
            }
        }     
        /// <summary>
        /// 全部保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISaveAll_Click(object sender, EventArgs e)
        {
            foreach (TabPage tp in tabControl1.TabPages)
            {
                foreach (Control cc in tp.Controls)
                {
                    if (cc is TextEditorControl)
                    {
                        TextEditorControl tec = (TextEditorControl)cc;
                        string path = tec.Tag.ToString();
                        tec.SaveFile(path);
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion


        #region Edit
                
        /// <summary>
        /// Undo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnUndo_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                currentEditor.Undo();
            }
        }
        /// <summary>
        /// Redo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnRedo_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                currentEditor.Redo();
            }
        } 
        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                if (HaveSelection(currentEditor))
                    DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.Copy());
            }
        }
        /// <summary>
        /// 粘贴
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.Paste());
            }
        }
        /// <summary>
        /// 剪切
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                if (HaveSelection(currentEditor))
                    DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.Cut());
            }
        }
        /// <summary>
        /// 全考到剪贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISelectAll_Click(object sender, EventArgs e)
        {
            Clipboard.SetDataObject(currentEditor.Text, true);
        }

        //===================================================================

        FindAndReplaceForm _findForm = new FindAndReplaceForm();
        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIFind_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            _findForm.ShowFor(currentEditor, false);
        }
        /// <summary>
        /// 替换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIFindReplace_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            _findForm.ShowFor(currentEditor, true);
        }
        /// <summary>
        /// 查找下一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIFindNext_Click(object sender, EventArgs e)
        {
            _findForm.FindNext(true, false,
            string.Format("没有找到你要查找的内容！", _findForm.LookFor));
        }
        /// <summary>
        /// 查找上一个
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIFindPrev_Click(object sender, EventArgs e)
        {
            _findForm.FindNext(true, true,
            string.Format("没有找到你要查找的内容！", _findForm.LookFor));
        }
        
        //===========================================================================

        /// <summary>
        /// 设置书签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIBookmarks_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.ToggleBookmark());
                currentEditor.IsIconBarVisible = currentEditor.Document.BookmarkManager.Marks.Count > 0;
            }
        }
        /// <summary>
        /// 下一个书签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMINextBookmarks_Click(object sender, EventArgs e)
        {
            DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.GotoNextBookmark(delegate(Bookmark bookmark)
                                                                                        {
                                                                                            return true;
                                                                                        }));
        }
        /// <summary>
        /// 上一个书签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIPrevBookmarks_Click(object sender, EventArgs e)
        {
            DoEditAction(currentEditor, new ICSharpCode.TextEditor.Actions.GotoPrevBookmark(delegate(Bookmark bookmark)
                                                                                        {
                                                                                            return true;
                                                                                        }));
        }


        #endregion


        #region View

        /// <summary>
        /// 分割窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISplitWindows_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.Split();
            OnSettingsChanged();
        }
        /// <summary>
        /// 显示空格与制表符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMISpace_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.ShowSpaces = currentEditor.ShowTabs = !currentEditor.ShowSpaces;
            OnSettingsChanged();
        }
        /// <summary>
        /// 显示换行符
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMILineR_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.ShowEOLMarkers = !currentEditor.ShowEOLMarkers;
            OnSettingsChanged();
        }
        /// <summary>
        /// 显示无效行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMILineNo_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.ShowInvalidLines = !currentEditor.ShowInvalidLines;
            OnSettingsChanged();
        }
        /// <summary>
        /// 显示行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMILineNum_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.ShowLineNumbers = !currentEditor.ShowLineNumbers;
            OnSettingsChanged();
        }
        /// <summary>
        /// 选中行高亮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIHighLight_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.LineViewerStyle = currentEditor.LineViewerStyle == LineViewerStyle.None
                ? LineViewerStyle.FullRow : LineViewerStyle.None;
            OnSettingsChanged();
        }
        /// <summary>
        /// 高亮匹配括号当光标在其后时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIBracketMatchingStyle_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.BracketMatchingStyle = currentEditor.BracketMatchingStyle == BracketMatchingStyle.After
                ? BracketMatchingStyle.Before : BracketMatchingStyle.After;
            OnSettingsChanged();
        }
        /// <summary>
        /// 制表符转为空格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMITabToSpace_Click(object sender, EventArgs e)
        {
            if (currentEditor == null) return;
            currentEditor.ConvertTabsToSpaces = !currentEditor.ConvertTabsToSpaces;
            OnSettingsChanged();
        }

        #endregion


        #region Option

        /// <summary>
        /// 字体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIFont_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                fontDialog1.Font = currentEditor.Font;
                if (fontDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    currentEditor.Font = fontDialog1.Font;
                    OnSettingsChanged();
                }
            }
        }
        /// <summary>
        /// 设置背景色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tdMIBackColor_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                using (ColorDialog cd = new ColorDialog())
                {
                    if (cd.ShowDialog() == DialogResult.OK)
                    {
                        currentEditor.BackColor = cd.Color;
                        currentEditor.Refresh();
                    }
                }
            }
        }
        /// <summary>
        /// 设置制表符大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMITabNum_Click(object sender, EventArgs e)
        {
            if (currentEditor != null)
            {
                string result = TabNumInputBox.Show("请指定制表符大小：", "制表符大小", currentEditor.TextEditorProperties.TabIndent.ToString());
                int value;
                if (result != null && int.TryParse(result, out value) && Globals.IsInRange(value, 1, 32))
                {
                    currentEditor.TabIndent = value;
                }
            }
        }


        #endregion


        #region Help
        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnAbout_Click(object sender, EventArgs e)
        {
            using (AboutBox ab = new AboutBox())
            {
                ab.ShowDialog();
            }
        }
        /// <summary>
        /// 帮助文档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIHelpContent_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start(String.Format("{0}{1}", Application.StartupPath, "\\CodeManagerHelp.chm"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #endregion


        #region 插入代码段
        int txtX;
        int txtY;
        int originalHeight = 164;
        int hideHeight = 21;

        string codeProperty = "<Property name=\"\" value=\"\" valueType=\"String\" fullType=\"\" accessibility=\"public\" returnType=\"\" attribute=\"\"></Property>";

        string codeEvent = "<Event name=\"\" value=\"\" valueType=\"String\" fullType=\"Event\" accessibility=\"private\" returnType=\"void\" attribute=\"\" eventArgs==\"EventArgs\"></Event>";

        string codeMethod = @"<Method name=""""  value="" valueType=""Method"" fullType="" accessibility="""" returnType=""""  attribute="""">
	<Parameter name=""""     value="""" valueType=""String"" fullType=""System.String"" returnType=""""  output=""""></Parameter>
</Method>";

        string codeField = "<Field name=\"\" value=\"\" valueType=\"\" fullType=\"\" accessibility=\"private\" returnType=\"\" attribute=\"\"></Field>";
    
        string codeOption = "<add key=\"\" value=\"\" />";


     
        private void tsMIInsertCode_Click(object sender, EventArgs e)
        {
            if(currentEditor==null) return;

            txtX = currentEditor.ActiveTextAreaControl.Caret.Column;
            txtY = currentEditor.ActiveTextAreaControl.Caret.Line;

            Point pp = currentEditor.PointToClient(Control.MousePosition);
            tlpInsertCode.Location = new Point(pp.X-5, pp.Y + txtInsertCode.Height-10);
            tlpInsertCode.Visible = true;
            tlpInsertCode.Height = originalHeight;
            tlpInsertCode.Select();
            tlpInsertCode.Focus();
        }

      
        private void treeInsertCode_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = tree1.CalcHitInfo(new Point(e.X, e.Y));
            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell) return;
            if (e.Button != MouseButtons.Left) return;
            if (treeInsertCode.Nodes.Count < 1) return;

            TxtEditorInsertCode(treeInsertCode.FocusedNode.GetValue(1).ToString());
        }
        

        /// <summary>
        /// 绑定菜单
        /// </summary>
        void BindInsertCodeTreeItem()
        {
            TreeListNode tln1 = treeInsertCode.AppendNode(null, null);
            tln1.StateImageIndex = 0;
            tln1.SetValue(0, "Property");
            tln1.SetValue(1, codeProperty);

            TreeListNode tln2 = treeInsertCode.AppendNode(null, null);
            tln2.StateImageIndex = 1;
            tln2.SetValue(0, "Event");
            tln2.SetValue(1, codeEvent);

            TreeListNode tln3 = treeInsertCode.AppendNode(null, null);
            tln3.StateImageIndex = 2;
            tln3.SetValue(0, "Method");
            tln3.SetValue(1, codeMethod);

            TreeListNode tln4 = treeInsertCode.AppendNode(null, null);
            tln4.StateImageIndex = 3;
            tln4.SetValue(0, "Field");
            tln4.SetValue(1, codeField);

            TreeListNode tln5 = treeInsertCode.AppendNode(null, null);
            tln5.StateImageIndex = 4;
            tln5.SetValue(0, "NewOption");
            tln5.SetValue(1, codeOption);
        }

        /// <summary>
        /// 代码插入方法
        /// </summary>
        /// <param name="code"></param>
        void TxtEditorInsertCode(string code)
        {
            currentEditor.ActiveTextAreaControl.TextArea.InsertString(code);
            //currentEditor.ActiveTextAreaControl.Caret.Column = txtX;
            //currentEditor.ActiveTextAreaControl.Caret.Line = txtY;
            currentEditor.ActiveTextAreaControl.Focus();
            currentEditor.ActiveTextAreaControl.Select();
            tlpInsertCode.Visible = false;
        }

        /// <summary>
        /// 插入框回车输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInsertCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!String.IsNullOrEmpty(txtInsertCode.Text.Trim()))
                {
                    string codeS = String.Format("<{0}></{0}>", txtInsertCode.Text.Trim());
                    TxtEditorInsertCode(codeS);
                }
                tlpInsertCode.Visible = false;
            }
        }

        /// <summary>
        /// 整个菜单离开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlpInsertCode_Leave(object sender, EventArgs e)
        {
            tlpInsertCode.Visible = false;
        }

        /// <summary>
        /// 插入框输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtInsertCode_Enter(object sender, EventArgs e)
        {
            tlpInsertCode.Height = hideHeight;
        }


        /*=====================工具条=================================*/


        private void tsBtnInsertProperty_Click(object sender, EventArgs e)
        {
            TxtEditorInsertCode(codeProperty);
        }

        private void tsBtnInsertEvent_Click(object sender, EventArgs e)
        {
            TxtEditorInsertCode(codeEvent);
        }

        private void tsBtnInsertMethod_Click(object sender, EventArgs e)
        {
            TxtEditorInsertCode(codeMethod);
        }

        private void tsBtnInsertField_Click(object sender, EventArgs e)
        {
            TxtEditorInsertCode(codeField);
        }
        
        private void tsBtnInsertOption_Click(object sender, EventArgs e)
        {
            TxtEditorInsertCode(codeOption);
        }

        #endregion


        #region 左侧树菜单

        private void cMIDiskFile_Click(object sender, EventArgs e)
        {
            StringBuilder filePath = new StringBuilder() ;
            filePath.Append(Application.StartupPath);
            filePath.Append("\\");
            if (tree1.Focused)
            {
                if (tree1.FocusedNode == null) return;
                switch (tree1.FocusedNode.GetValue(2).ToString())
                {
                    case "c":
                        filePath.Append(PubConstant.ConfigPath);
                        break;
                    case "t":
                        filePath.Append(PubConstant.TemplatePath);
                        break;
                }
                filePath.Append(tree1.FocusedNode.GetValue(1).ToString());   
            }
            else 
            {
                if (tree2.FocusedNode == null) return;
                if (tree2.FocusedNode.GetValue(1).ToString() == "Folder") return;
                filePath.Append(PubConstant.TemplatePath);
                filePath.Append(tree2.FocusedNode.GetValue(0).ToString());
            }
            filePath.Append(".xml");
            string cmd=String.Format("cmd /c explorer /select, {0}",filePath.ToString());

            Process pro = new Process();
            pro.StartInfo.FileName = "explorer";
            pro.StartInfo.Arguments = @"/select," + filePath.ToString();
            pro.Start();


            //Process pro = new Process();
            //pro.StartInfo.FileName = "cmd.exe";//要执行的程序名称 
            //pro.StartInfo.UseShellExecute = false;
            //pro.StartInfo.RedirectStandardInput=true;//可能接受来自调用程序的输入信息 
            //pro.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 
            //pro.StartInfo.CreateNoWindow = true;//不显示程序窗口 
            //pro.Start();//启动程序 
            ////向CMD窗口发送输入信息： 
            //pro.StandardInput.WriteLine(cmd);  

            //pro.StandardInput.WriteLine("shutdown -r t 10")//10秒后重启（C#中可不好做哦）
            //获取CMD窗口的输出信息： 
            //string sOutput = pro.StandardOutput.ReadToEnd();
            
        }

        #region 上

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSort1_Click(object sender, EventArgs e)
        {
            tree1.Columns[0].SortOrder = SortOrder.Ascending;
        }
        /// <summary>
        /// 显示全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnAll_ButtonClick(object sender, EventArgs e)
        {
            tree1.FilterConditions[0].Visible = true;
            tree1.FilterConditions[1].Visible = true;
            tree1.Refresh();
        }
        /// <summary>
        /// 显示设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIc_Click(object sender, EventArgs e)
        {
            tree1.FilterConditions[0].Visible = true;
            tree1.FilterConditions[1].Visible = false;
            tree1.Refresh();
        }
        /// <summary>
        /// 显示模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsMIm_Click(object sender, EventArgs e)
        {
            tree1.FilterConditions[0].Visible = false;
            tree1.FilterConditions[1].Visible = true;
            tree1.Refresh();
        }
        #endregion

        #region 下
        
        private void tsBtnNewControlTemp_Click(object sender, EventArgs e)
        {
            txtNewTemp.Text = "";
            panelNewTemp.Visible = true;

        }

        void CreateNewTempFile(string path)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                fs = new FileStream(path, FileMode.Create, FileAccess.Write);//创建写入文件   
                sw = new StreamWriter(fs);
                sw.WriteLine("<Object name=\"\" type=\"\"  accessibility=\"\" children=\"\">");
                sw.WriteLine("    <Property name=\"\" value=\"\" valueType=\"\" fullType=\"\" accessibility=\"\" returnType=\"\" attribute=\"\"></Property>");
                sw.WriteLine("    <Property name=\"\" value=\"\" valueType=\"\" fullType=\"\" accessibility=\"\" returnType=\"\" attribute=\"\"></Property>");
                sw.WriteLine("</Object>");
            }
            catch (Exception ex)
            {
                PPCodes.Log.FileLogger.Instance.ToError("CreateNewTempFile()-ERROR", ex);
                throw ex;
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
        }

        private void txtNewTemp_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (String.IsNullOrEmpty(txtNewTemp.Text.Trim()))
                {
                    panelNewTemp.Visible = false;
                    return;
                }
                if (txtNewTemp.Text.Trim().IndexOf('-') == -1)
                {
                    MessageBox.Show("模板名不合规范，正规格式  \"前缀-名称\" ");
                    return;
                }
                else
                {
                    string path = String.Format("{0}\\{1}{2}.xml", Application.StartupPath, PubConstant.TemplatePath, txtNewTemp.Text.Trim());
                    if (File.Exists(path))
                    {
                        if (MessageBox.Show("已存在相同名称文件是否覆盖？", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            File.Delete(path);
                            CreateNewTempFile(path);
                        }
                        else
                        {
                            return;
                        }
                    }
                    else
                    {
                        CreateNewTempFile(path);
                    }
                }
                LoadControlTempTreeItem();
                panelNewTemp.Visible = false;
            }

        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancelTemp_Click(object sender, EventArgs e)
        {
            txtNewTemp.Text = "";
            panelNewTemp.Visible = false;
        }
        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnTempRefrech_Click(object sender, EventArgs e)
        {
            LoadControlTempTreeItem();
        }
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsBtnSort2_Click(object sender, EventArgs e)
        {
            tree2.Columns[0].SortOrder = SortOrder.Ascending;
        } 
        #endregion




        #endregion














    }
}
